import { FC, useState, useReducer, createContext } from "react";
import { useTitle } from "ahooks";
import List from "./com/List";
import reducer, { type ActionType } from "./reducer";
import initialState from "./store";
import styled from "styled-components";

const FormContainer = styled.form`
  text-align: center;
  width: 600px;
  margin: 0px auto;
  padding-top: 20px;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  input {
    height: 32px;
    width: 100%;
    padding: 0px 5px;
    border-radius: 5px;
    &:focus-visible {
      outline: none;
    }
  }
`;
export const TodoContext = createContext({
  state: initialState,
  dispatch: (action: ActionType) => {
    console.log(action);
  },
});
const Reducer: FC = () => {
  useTitle("Reducer Demo");
  const [state, dispatch] = useReducer(reducer, initialState);
  const [keyword, setKeyword] = useState("");
  const handleAdd = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (!keyword) return;
    if (e.keyCode === 13) {
      const newTodo = { id: Date.now() + "", title: keyword };
      dispatch({ type: "add", payload: newTodo });
      setKeyword("");
    }
  };
  return (
    <TodoContext.Provider value={{ state, dispatch }}>
      <FormContainer className="todo" onSubmit={(e) => e.preventDefault()}>
        <input
          type="text"
          onChange={(e) => setKeyword(e.target.value)}
          onKeyDown={handleAdd}
          value={keyword}
        />
        <List></List>
      </FormContainer>
    </TodoContext.Provider>
  );
};

export default Reducer;
